package com.example.myapplication.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @Author ymz0427
 * 1、LifecycleOwner结束后移除相关的Runnable
 * 2、Runnable执行结束，移除对应的Runnable
 */
public class MainHandler {


    private final Handler handler;

    private MainHandler(@NonNull Looper looper) {
        handler = new Handler(looper);
    }

    //存储生命周期
    private final Map<Lifecycle, RunnableObserver> map = new ConcurrentHashMap<>();

    private static MainHandler myHandler;

    public static MainHandler getInstance() {
        if (myHandler == null) {
            synchronized (MainHandler.class) {
                if (myHandler == null) {
                    myHandler = new MainHandler(Looper.getMainLooper());
                }
            }
        }
        return myHandler;
    }

    public boolean post(@NonNull Lifecycle lifecycle, Runnable runnable) {
        return postDelayed(lifecycle, runnable, 0);
    }

    //根据runnable移除，待完善
    public boolean postDelayed(@NonNull Lifecycle lifecycle, @NonNull Runnable runnable,
                               long delayMillis) {
        RunnableObserver observer = map.get(lifecycle);
        if (observer == null) {
            observer = new RunnableObserver(map);
            lifecycle.addObserver(observer);
            map.put(lifecycle, observer);
        }
        LifecycleRunnable tmp = new LifecycleRunnable(runnable, observer);
        observer.add(tmp);
        return handler.postDelayed(tmp, delayMillis);
    }



    public void remove(@NonNull Lifecycle lifecycle, @NonNull Callback callback) {
        //todo:
    }

//    public void remove(@NonNull Lifecycle lifecycle, @NonNull Runnable runnable) {
//        //todo
//    }
//
//    public boolean sendMessage(@NonNull Lifecycle lifecycle, @NonNull Message message,
//                               @NonNull Callback callback) {
//        return sendMessageDelayed(lifecycle, message, callback, 0);
//    }
//
//    public boolean sendMessageDelayed(@NonNull Lifecycle lifecycle, @NonNull Message message,
//                                      @NonNull Callback callback, long delayMillis) {
//        return postDelayed(lifecycle, new CallbackMessage(message, callback), delayMillis);
//    }
}
